<!DOCTYPE html>
<html>
	<head>
		<meta charset="UTF-8">
		<title>自定义指令实现随机背景色</title>
    <style>
      div {
        width: 300px;
        height: 300px;
      }
    </style>
	</head>
	<body>
		<div id="app">
			<div v-img="'images/bg.jpg'"></div>
		</div>
	
		<script src="https://unpkg.com/vue@next"></script>
		<script>
      const app = Vue.createApp({})
      app.directive('img', {
        mounted(el, binding){
          let color = Math.floor(Math.random() * 1000000)
          el.style.backgroundColor = '#' + color
          let img = new Image();
          img.src = binding.value
          img.onload = function(){
            alert("paused")
            el.style.backgroundImage = 'url(' + binding.value + ')'
          }
        }
      })
      app.mount('#app')
    </script>
	</body>
</html>

